<template>
  <div class="app-container">
    <div class="contentDiv">
      <div class="tx-r" style="margin-bottom: 10px">
        <el-button v-permiss="['702010']" size="small" type="primary" :loading="saveloading" round :disabled="storeStatus == 0" @click="saveData(0)">保存</el-button>
        <el-button v-permiss="['704020']" size="small" type="primary" :disabled="storeStatus == 0" round @click="handImport">导入</el-button>
      </div>
      <el-table v-loading="listLoading" class="balance" :data="tableData" border stripe fit resize style="width: 100%;" :height="tableHeight" cell-class-name="tdCell">
        <el-table-column align="center" label="仓库" min-width="80">
          <template slot-scope="scope">
            <warehouseList key-type="warehouseId" :select-id="scope.row.warehouseCode" :index="scope.$index" :place-txt="null" @selectChange="changeVal1" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="存货" min-width="80">
          <template slot-scope="scope">
            <itemList :select-id="scope.row.itemId" :select-code="scope.row.itemCode" :index="scope.$index" @changeVal="changeVal2" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="批次号" min-width="80">
          <template slot-scope="{row}">
            <input v-model.trim="row.batchNo" class="tx-r inputCell" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" min-width="60">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.beginBalanceQtyDr" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'beginBalanceQtyDr', scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="平均成本价" min-width="80">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.wmap" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'wmap', scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="right" label="金额(元)" min-width="80">
          <template slot-scope="scope">
            <span style="padding-right:8px">{{ scope.row.beginBalanceDr }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="本年入库数量" min-width="80">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.yearNetQryDr" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'yearNetQryDr', scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="本年入库金额" min-width="80">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.yearNetDr" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'yearNetDr', scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="本年出库数量" min-width="80">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.yearNetQryCr" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'yearNetQryCr', scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="本年出库金额" min-width="80">
          <template slot-scope="scope">
            <input v-model.trim="scope.row.yearNetCr" class="tx-r inputCell" @focus="focusThis($event)" @input="inputChange($event, 'yearNetCr', scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="导入库存" :visible.sync="dialogVisible" width="450px">
      <el-form ref="importForm" :model="importForm" label-position="left" label-width="0" style="margin-left:10px;">
        <el-form-item label prop="fileName" :rules="fileRule">
          <el-upload dragle action="/" accept=".xls, .xlsx" :auto-upload="false" :show-file-list="false" :file-list="fileList" :on-change="importFile">
            <div class="fileDiv">
              <span v-if="importForm.fileName" style="margin-right:5px">{{ importForm.fileName }}</span>
              <el-button type="text">{{ fileList.length === 0 ? '点击上传' : '重新上传' }}</el-button>
            </div>
          </el-upload>
        </el-form-item>
        <div style="height:32px" class="tx-l">
          <el-button type="text" @click="downloadTemplate">下载模板</el-button>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="handleImport()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getStore, importStore, updateStore } from '@/api/user'
import { validateVal } from '@/utils'
import { deleteEmptyProp, addNullObj } from '@/utils'
import warehouseList from '@/components/selects/warehouseList'
import itemList from '@/components/selects/itemList'
export default {
  name: 'InitialBalance',
  components: {
    warehouseList, itemList
  },
  data() {
    return {
      dialogVisible: false,
      listLoading: false,
      saveloading: false,
      storeStatus: 0,
      tableData: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
      tableHeight: document.body.clientHeight - 183,
      importForm: {
        fileName: ''
      },
      fileRule: [
        { required: true, message: '请选择要导入的文件！', trigger: 'change' }
      ],
      fileList: []
    }
  },
  created() {
    this.$store.dispatch('basedata/getitemlist')
    this.getData()
  },
  methods: {
    changeVal1(obj) {
      this.$set(this.tableData[obj.index], 'warehouseCode', obj['warehouseId'])
    },
    changeVal2(obj) {
      this.$set(this.tableData[obj.index], 'itemCode', obj['itemId'])
    },
    downloadTemplate() {
      location.href = 'business/inventory.xlsx'
    },
    handImport() {
      this.dialogVisible = true
    },
    importFile(file, fileList) {
      this.formData = new FormData()
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
      this.formData.append('file', file.raw)
      this.importForm.fileName = file.name
      this.$refs.importForm.validateField('fileName')
    },
    handleImport() {
      this.$refs.importForm.validate((valid) => {
        if (valid) {
          const obj = this.formData
          importStore(obj).then((res) => {
            if (res.data.errorCode === '0') {
              this.$message.success(res.data.msg)
              this.dialogVisible = false
              this.getData()
            }
          })
        }
      })
    },
    inputChange(e, param, index) {
      var num = validateVal(e.currentTarget.value)
      this.$set(this.tableData[index], param, num)
      if (param === 'wmap' || param === 'beginBalanceQtyDr') {
        if (this.tableData[index].wmap && this.tableData[index].beginBalanceQtyDr) {
          const num = Number(this.tableData[index].wmap) * Number(this.tableData[index].beginBalanceQtyDr)
          this.$set(this.tableData[index], 'beginBalanceDr', num)
        }
      }
    },
    focusThis(e) {
      e.currentTarget.select()
    },
    saveData(type) {
      this.saveloading = true
      const arr = deleteEmptyProp(this.tableData)
      updateStore(arr).then((res) => {
        this.saveloading = false
        if (res.data.errorCode === '0') {
          this.$message.success(res.data.msg)
        }
      }).catch(() => {
        this.saveloading = false
      })
    },
    getData() {
      this.listLoading = true
      getStore().then((res) => {
        this.storeStatus = 1
        this.listLoading = false
        this.tableData = addNullObj(res.data.data)
      }).catch(() => {
        this.listLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
>>> .el-form-item {
  margin-bottom: 20px;
}

.fileDiv {
  width: 400px;
  height: 60px;
  border: 1px #d0d0d0 solid;
  line-height: 60px;
  text-align: center;
  border-radius: 6px;
}
.filter-item {
  position: relative;
}
</style>
